package com.wanshi.member.filter;

import com.alibaba.fastjson.JSON;
import com.wanshi.member.base.Result;
import com.wanshi.member.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 */
@Component
public class AuthenticationFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 是否登录
        boolean isLogin = false;

        // 请求头带上令牌 Authorization: Bearer jwtToken
        final String authHeader = request.getHeader("Authorization");


        try{

            if(StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")) {
                // 截取token，
                final String token = authHeader.substring(7);
                // 解析token
                Claims claims = jwtUtil.parseJWT(token);
                if(claims != null) {
                    // 是否登录
                    Boolean b = (Boolean) claims.get("isLogin");
                    if(b) {
                        // 已经登录，放行请求
                        isLogin = true;
                    }
                }
            }

        }catch (MalformedJwtException e){

        }


        if(!isLogin) {
            // 未登录，则响应信息
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            //response.setStatus(401);

            //Result r = Result.nologin();
            response.getWriter().write( JSON.toJSONString( Result.nologin()  ));
        }
        // 放行
        return isLogin;

        //return true;
    }
}
